<template>
  <div class="card">
    <dv-border-box-11 title="xx外宣" :color="['#168BF9', '#112F7C']">
      <!-- 外宣趋势图表 -->
      <div class="trend-section">
        <div class="section-bg">
          <div class="chart-title">外宣趋势(近半年)</div>
          <div class="chart-content">
            <div ref="trendChart" class="chart"></div>
          </div>
        </div>
      </div>

      <!-- Element UI 单选按钮组和表格 -->
      <div class="media-section">
        <div class="section-bg">
          <div class="media-header">
            <div class="chart-title">媒体报道</div>
            <div class="radio-container">
              <el-radio-group v-model="activeTab" @change="handleTabChange">
                <el-radio-button label="中央媒体">央媒看酉阳</el-radio-button>
                <el-radio-button label="市属媒体">市媒看酉阳</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div class="content-container">
            <div class="table-container">
              <el-table
                :data="tableData"
                style="width: 100%"
                highlight-current-row
                class="dark-blue-table"
                :height="200"
                @row-click="handleRowClick"
              >
                <el-table-column
                  prop="address"
                  label="标题"
                  min-width="150"
                  :show-overflow-tooltip="true"
                >
                  <template slot-scope="scope">
                    <div class="title-cell">{{ scope.row.address }}</div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="name"
                  label="账号"
                  width="100"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  prop="date"
                  label="时间"
                  width="120"
                  align="center"
                >
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
    </dv-border-box-11>

    <!-- 文章详情弹窗 -->
    <div v-if="articlePopupVisible" class="cockpit-popup" :style="popupStyle">
      <div class="cockpit-popup-content">
        <div class="popup-header">
          <h2 class="popup-title">
            {{ selectedArticle.address || "文章详情" }}
          </h2>
          <button class="close-btn" @click="closeArticlePopup">×</button>
        </div>
        <div class="popup-body">
          <div class="article-info">
            <p>
              <strong>账号:</strong>
              <span class="data-text">{{ selectedArticle.name }}</span>
            </p>
            <p>
              <strong>发布时间:</strong>
              <span class="data-text">{{ selectedArticle.date }}</span>
            </p>
            <p>
              <strong>媒体级别:</strong>
              <span class="data-text">{{ selectedArticle.level }}</span>
            </p>
            <p>
              <strong>渠道:</strong>
              <span class="data-text">{{ selectedArticle.channel }}</span>
            </p>
            <p>
              <strong>原文链接:</strong>
              <a
                :href="selectedArticle.url"
                target="_blank"
                class="article-link"
                @click.stop
              >
                {{ selectedArticle.url }}
              </a>
            </p>
          </div>
          <div class="article-preview" v-if="showArticlePreview">
            <iframe
              :src="selectedArticle.url"
              class="article-iframe"
              frameborder="0"
              @load="onIframeLoad"
              @error="onIframeError"
            ></iframe>
            <div v-if="iframeLoading" class="loading-message">
              正在加载原文...
            </div>
            <div v-if="iframeError" class="error-message">无法加载原文内容</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { currentPOST } from "api/modules";
import * as echarts from "echarts";
import { mapState } from "vuex";

export default {
  data() {
    return {
      activeTab: "中央媒体",
      tableData: [],
      trendChart: null,
      // 趋势图数据 - 初始化为空
      trendData: {
        dates: [], // 动态设置横坐标
        centralMedia: [], // 中央媒体数据
        localMedia: [], // 市属媒体数据
      },
      // 文章弹窗相关数据
      articlePopupVisible: false,
      selectedArticle: {},
      iframeLoading: false,
      iframeError: false,
      showArticlePreview: true,
      // 弹窗尺寸配置
      popupSize: {
        width: "80%",
        height: "80%",
      },
    };
  },
  computed: {
    ...mapState(["lastDay"]),
    // 弹窗样式计算属性
    popupStyle() {
      return {
        width: this.popupSize.width,
        height: this.popupSize.height,
        minHeight: "400px",
        maxWidth: "1200px",
        maxHeight: "800px",
      };
    },
  },
  watch: {
    // 监听lastDay的变化，当变化时重新获取数据
    lastDay(newVal) {
      this.getTrendData();
      this.getArticleData();
    },
  },
  created() {
    this.getArticleData();
  },
  mounted() {
    this.getTrendData();
    this.$nextTick(() => {
      this.initTrendChart();
    });
  },
  beforeDestroy() {
    this.clearData();
    if (this.trendChart) {
      this.trendChart.dispose();
    }
    window.removeEventListener("resize", this.handleChartResize);
  },
  methods: {
    clearData() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },

    getArticleData() {
      currentPOST("rightTopArticleHome", {
        lastDay: this.lastDay,
        pageSize: 100,
        current: 1,
        levels: [this.activeTab], // 将选中的tab值传入接口
      })
        .then((res) => {
          if (res.code === 0) {
            this.processArticleData(res.data);
          } else {
            this.$Message({
              text: res.msg,
              type: "warning",
            });
          }
        })
        .catch((error) => {
          console.error("文章请求失败:", error);
        });
    },

    // 处理媒体报道数据
    processArticleData(responseData) {
      if (
        !responseData ||
        !responseData.data ||
        !Array.isArray(responseData.data)
      ) {
        console.warn("媒体报道数据格式不正确");
        this.tableData = [];
        return;
      }

      const articles = responseData.data;

      // 将接口数据映射为表格需要的格式
      this.tableData = articles.map((article) => {
        // 格式化时间，只显示月-日 时:分
        const releaseTime = this.formatDateTime(article.dataReleaseTime);

        return {
          address: article.dataName || "--", // dataName -> address（标题）
          name: article.source || "--", // source -> name（账号）
          date: releaseTime || "--", // 发布时间
          // 保留其他可能需要的数据
          level: article.level,
          channel: article.channel,
          url: article.dataUrl,
        };
      });
    },

    // 处理行点击事件
    handleRowClick(row, column, event) {
      // 只有当点击标题列时才打开弹窗
      if (column.property === "address" && row.url) {
        this.openArticlePopup(row);
      }
    },

    // 打开文章弹窗
    openArticlePopup(article) {
      this.selectedArticle = { ...article };
      this.articlePopupVisible = true;
      this.iframeLoading = true;
      this.iframeError = false;
    },

    // 关闭文章弹窗
    closeArticlePopup() {
      this.articlePopupVisible = false;
      this.selectedArticle = {};
      this.iframeLoading = false;
      this.iframeError = false;
    },

    // 在新标签页打开文章
    openInNewTab() {
      if (this.selectedArticle.url) {
        window.open(this.selectedArticle.url, "_blank");
      }
    },

    // iframe加载完成
    onIframeLoad() {
      this.iframeLoading = false;
      this.iframeError = false;
    },

    // iframe加载错误
    onIframeError() {
      this.iframeLoading = false;
      this.iframeError = true;
    },

    // 格式化日期时间
    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return "";

      try {
        // 处理可能的字符串格式
        let dateStr = dateTimeStr;
        if (dateStr.includes("T")) {
          dateStr = dateStr.replace("T", " ").split(".")[0];
        }

        const date = new Date(dateStr);
        if (isNaN(date.getTime())) {
          return dateTimeStr;
        }

        const month = (date.getMonth() + 1).toString().padStart(2, "0");
        const day = date.getDate().toString().padStart(2, "0");
        const hours = date.getHours().toString().padStart(2, "0");
        const minutes = date.getMinutes().toString().padStart(2, "0");

        return `${month}-${day} ${hours}:${minutes}`;
      } catch (error) {
        return dateTimeStr;
      }
    },

    getTrendData() {
      currentPOST("rightTopTrendHome", {
        lastDay: this.lastDay,
        pageSize: "100",
        current: "1",
      })
        .then((res) => {
          if (res.code === 0) {
            this.processTrendData(res.data);
          } else {
            this.$Message({
              text: res.msg,
              type: "warning",
            });
          }
        })
        .catch((error) => {
          console.error("趋势数据请求失败:", error);
        });
    },

    // 处理趋势数据
    processTrendData(apiData) {
      if (!apiData || !Array.isArray(apiData)) {
        console.warn("趋势数据格式不正确");
        return;
      }

      // 从接口数据中提取所有唯一的日期
      const allDates = [...new Set(apiData.map((item) => item.date))];

      // 对日期进行排序（假设日期格式为 "YYYY-MM"）
      const sortedDates = allDates.sort((a, b) => {
        const dateA = new Date(a);
        const dateB = new Date(b);
        return dateA - dateB;
      });

      // 格式化横坐标显示（显示为月份）
      const formattedDates = sortedDates.map((date) => {
        // 假设日期格式为 "YYYY-MM"，提取月份
        const month = date.split("-")[1];
        return `${parseInt(month)}月`;
      });

      // 初始化数据数组
      const centralMedia = new Array(sortedDates.length).fill(0);
      const localMedia = new Array(sortedDates.length).fill(0);

      // 处理返回的数据
      apiData.forEach((item) => {
        const dateIndex = sortedDates.indexOf(item.date);
        if (dateIndex !== -1) {
          const count = parseInt(item.count) || 0;
          if (item.level === "中央媒体") {
            centralMedia[dateIndex] = count;
          } else if (item.level === "市属媒体") {
            localMedia[dateIndex] = count;
          }
        }
      });

      // 更新趋势数据
      this.trendData.dates = formattedDates;
      this.trendData.centralMedia = centralMedia;
      this.trendData.localMedia = localMedia;

      // 重新渲染图表
      this.updateTrendChart();
    },

    // 初始化趋势图表
    initTrendChart() {
      if (this.$refs.trendChart) {
        this.trendChart = echarts.init(this.$refs.trendChart);
        this.updateTrendChart();
        window.addEventListener("resize", this.handleChartResize);
      }
    },

    // 更新趋势图表
    updateTrendChart() {
      if (!this.trendChart) return;

      const option = {
        tooltip: {
          trigger: "axis",
          backgroundColor: "rgba(5, 64, 128, 0.9)",
          borderColor: "#1890ff",
          textStyle: {
            color: "#bae7ff",
          },
          formatter: function (params) {
            let result = `${params[0].axisValue}<br/>`;
            params.forEach((item) => {
              result += `${item.marker} ${item.seriesName}: ${item.value}篇<br/>`;
            });
            return result;
          },
        },
        legend: {
          data: ["中央媒体", "市属媒体"],
          right: 10,
          top: 0,
          textStyle: {
            color: "#bae7ff",
            fontSize: 12,
          },
          itemWidth: 12,
          itemHeight: 8,
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          top: "15%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: this.trendData.dates,
          axisLine: {
            lineStyle: {
              color: "#2d5278",
            },
          },
          axisLabel: {
            color: "#bae7ff",
            fontSize: 11,
          },
          axisTick: {
            show: false,
          },
        },
        yAxis: {
          type: "value",
          name: "数量（篇）",
          nameTextStyle: {
            color: "#bae7ff",
            fontSize: 12,
          },
          axisLine: {
            lineStyle: {
              color: "#2d5278",
            },
          },
          axisLabel: {
            color: "#bae7ff",
            fontSize: 11,
          },
          splitLine: {
            lineStyle: {
              color: "rgba(45, 82, 120, 0.3)",
              type: "dashed",
            },
          },
        },
        series: [
          {
            name: "中央媒体",
            type: "line",
            data: this.trendData.centralMedia,
            smooth: true,
            symbol: "circle",
            symbolSize: 6,
            lineStyle: {
              color: "#1890ff",
              width: 3,
            },
            itemStyle: {
              color: "#1890ff",
              borderColor: "#ffffff",
              borderWidth: 1,
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgba(24, 144, 255, 0.3)" },
                { offset: 1, color: "rgba(24, 144, 255, 0.05)" },
              ]),
            },
          },
          {
            name: "市属媒体",
            type: "line",
            data: this.trendData.localMedia,
            smooth: true,
            symbol: "circle",
            symbolSize: 6,
            lineStyle: {
              color: "#52c41a",
              width: 3,
            },
            itemStyle: {
              color: "#52c41a",
              borderColor: "#ffffff",
              borderWidth: 1,
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgba(82, 196, 26, 0.3)" },
                { offset: 1, color: "rgba(82, 196, 26, 0.05)" },
              ]),
            },
          },
        ],
      };

      this.trendChart.setOption(option);
    },

    handleChartResize() {
      if (this.trendChart) {
        this.trendChart.resize();
      }
    },

    // Tab切换处理
    handleTabChange() {
      this.getArticleData(); // 切换tab时重新加载表格数据
    },
  },
};
</script>

<style lang="scss" scoped>
.card {
  margin-top: 30px;
  height: 550px;
  display: flex;
  justify-content: center;
}

.trend-section {
  margin-top: 35px;
  height: 200px;
  padding: 15px 20px 5px;
}

.media-section {
  height: calc(100% - 235px);
  padding: 5px 20px 15px;
  margin-top: 20px;
}

.section-bg {
  border-radius: 8px;
  padding: 15px;
  height: 90%;
  position: relative;
  display: flex;
  flex-direction: column;
}

.media-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  flex-shrink: 0;
}

.chart-title {
  color: #bae7ff;
  font-size: 16px;
  font-weight: 500;
  flex-shrink: 0;
}

.chart-content {
  flex: 1;
  position: relative;
  margin-top: 15px;
  .chart {
    width: 100%;
    height: 185px;
  }
}

.content-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.radio-container {
  display: flex;
  flex-shrink: 0;
}

.table-container {
  flex: 1;
  position: relative;
  min-height: 0;
  overflow: hidden;
}

// 标题单元格样式
.title-cell {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
  cursor: pointer;

}

::v-deep .el-radio-group {
  .el-radio-button {
    .el-radio-button__inner {
      background: linear-gradient(135deg, #1a3a5f 0%, #2d5278 100%);
      color: #bae7ff;
      border: 1px solid #2d5278;
      font-size: 14px;
      font-weight: 500;
      padding: 8px 16px;

      &:hover {
        color: #ffffff;
        background: linear-gradient(135deg, #2d5278 0%, #3a6ea5 100%);
      }
    }

    &.is-active {
      .el-radio-button__inner {
        background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
        color: #ffffff;
        border-color: #1890ff;
        box-shadow: 0 0 8px rgba(24, 144, 255, 0.5);
      }
    }
  }
}

// 表格样式调整
::v-deep .dark-blue-table {
  background: transparent;

  .el-table__header-wrapper,
  .el-table__body-wrapper {
    background: transparent;
  }

  .el-table__header {
    th {
      background: rgba(5, 64, 128, 0.8);
      color: #bae7ff;
      border-bottom: 1px solid #2d5278;
    }
  }

  .el-table__body {
    tr {
      background: transparent;
      cursor: pointer;

      td {
        background: transparent;
        color: #bae7ff;
        border-bottom: 1px solid rgba(45, 82, 120, 0.3);
      }

      &:hover > td {
        background: rgba(24, 144, 255, 0.1);
      }

      &.current-row > td {
        background: rgba(24, 144, 255, 0.2);
      }
    }
  }
}

/* 文章弹窗样式 */
.article-info {
  margin-bottom: 20px;
  p {
    margin: 8px 0;
    display: flex;
    align-items: center;
  }
  strong {
    color: #bae7ff;
    margin-right: 8px;
    min-width: 80px;
  }
}

.article-link {
  color: #1890ff;
  text-decoration: none;
  word-break: break-all;
  &:hover {
    text-decoration: underline;
    color: #40a9ff;
  }
}

.article-preview {
  position: relative;
  height: 500px;
  border: 1px solid #1890ff;
  border-radius: 4px;
  overflow: hidden;
  margin-top: 15px;
}

.article-iframe {
  width: 100%;
  height: 100%;
  background: white;
}

.loading-message,
.error-message {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #bae7ff;
  font-size: 16px;
  text-align: center;
}

.error-message {
  color: #ff7875;
}



</style>
